#include "stdafx.h"
#include "ElasticServer.h"
#include "Chennel.h"
#include "Prefs.h"

ElasticServer::ElasticServer(void)
{
}

ElasticServer::~ElasticServer(void)
{
}
int ElasticServer::SendTo(const char * index_suffix,const char * type,const char * data,int size)
{
	char buffer[2048];
	CChennel chennel(gPrefs->mServer,gPrefs->mPort);
	if( chennel.OpenChennel()<0 ){
		Trace::traceEvent(TRACE_ERROR,"can not open %s:%d",gPrefs->mServer,gPrefs->mPort);
		return -1;
	}
	Trace::traceEvent(TRACE_DEBUG,"connected to  %s:%d",gPrefs->mServer,gPrefs->mPort);
	memset(buffer,0,sizeof(buffer));
	sprintf(buffer,"POST /%s-%s/%s/ HTTP/1.1\r\nHost:%s\r\nAccept:*/*\r\nContent-type: application/json\r\nContent-Length:%d\r\n\r\n",
		gPrefs->mIndex,index_suffix,type,gPrefs->mDomain,size);
	Trace::traceEvent(TRACE_INFO,"Send Request: POST /%s-%s/%s/ [%d]%s",gPrefs->mIndex,index_suffix,type,size,data);
	chennel.WriteData(buffer,strlen(buffer));
	chennel.WriteData(data,size);
	memset(buffer,0,sizeof(buffer));

    int offset =0;
	int content = 2048;
	int bytes;
	char * cp;
	while(!chennel.IsClose() ){
		if( chennel.CanRead()>0 ){
			bytes = chennel.ReadData(buffer+offset,sizeof(buffer)-offset);
			if( bytes == 0 ) break;
			offset += bytes;
			cp = strstr(buffer,"\r\n\r\n"); 
			if( cp ){
				cp[0]=0;
				Trace::traceEvent(TRACE_DEBUG,"Respone Head:%s",buffer);
				data = cp+4;
				cp = strstr(buffer,"content-length:");
				if( cp ){
					content = atoi(cp+15);
				}
				memmove(buffer,data,strlen(data)+1);
				break;
			}
		} else SLEEP(2);
	}
	offset =strlen(buffer);
	while(!chennel.IsClose() && offset < content){
		if( chennel.CanRead()>0 ){
			bytes = chennel.ReadData(buffer+offset,sizeof(buffer)-offset);
			if( bytes == 0 ) break;
			offset += bytes;
			if( strstr(buffer,"\r\n\r\n") ) break;
		} else SLEEP(2);
	}
	chennel.CloseChennel();
	Trace::traceEvent(TRACE_INFO,"Respone Data:%s",buffer);
	cp = strchr(buffer,':');
	if(cp) cp = strchr(cp+1,':');
	if( cp ) cp[0]=0;
	if( strstr(buffer,"error") ) return 0;
    return 1;
}